'use strict';

var router = require('express').Router();
var crypto = require('crypto');

var mysql = require('mysql');
var Sequelize = require('sequelize');
var ErrorCode = require('./err');
var Comset = require('../comset');

//用户表
var User= require('../sqlmodels/users');

//短信表
var SmsSequelize = require('../sqlmodels/smscode')
var sequelize =  SmsSequelize.sequelize;
var comFunc = require('../comfunc');


//修改用户信息
function editUserMessage(params,callback){
	if(params.phone){
		User.findOne({
			where:{
				phone:params.phone
			}
		}).then(function(results){
			if(results){
				return callback(ErrorCode.sameMobile)
			}else{
				User.update(params,{
					where:{
						user_id:params.user_id
					}
				}).then(function(result){
			        return callback(ErrorCode.true)
				}, function(err){
					return callback(ErrorCode.sameMobile)
				})
			}
		})
	}else{
		User.findOne({
			where:{
				user_id:params.user_id
			}
		}).then(function(results){
			if(!results){
				return callback(ErrorCode.canNotFindUser)
			}else{
				User.update(params,{
					where:{
						user_id:params.user_id
					}
				}).then(function(result){
			        return callback(ErrorCode.true)
				}, function(err){
					return callback(ErrorCode.sameMobile)
				})
			}
		})
	}
}

//查询用户信息
function userMessage(params,callback){
	User.findOne({
		where:{
			id: params.user_id
		},
		attributes:['name','phone','email','headurl','vipstarttime','vipendtime','nickname']
	}).then(function(result){
		var results = result;
		if(!results.dataValues.headurl){
			results.headurl = Comset.headImg;
		}
		var data = {
			code:'1',
			message:'success',
			datas:results
		}
		return callback(data);
	}, function(err){
		return callback(err);
	})
}

//获取用户Id等信息
function getUserId(params,callback){
	User.findOne({
		where:{
			sessiontoken : params
		},
		attributes: ['id','name','headurl']
	}).then(function(result){
		if(result){
			var data = {
				code:'1',
				id : result.dataValues.id,
				userid:result.dataValues.id,
				headurl:result.dataValues.headurl,
				name:result.dataValues.name
			}
			return callback(null, data);
		}
		else{
			return callback(ErrorCode.canNotFindUser,null)
		}
         }, function(err){
            return callback(err,null);
         })
}

//获取用户Id，Promise封装
function getUserIdPromise(params){
	var promise = new AV.Promise(function(resolve,reject){
		getUserId(params,function(err,result){
			if(err){
				resolve(err);
			}else{
				resolve(result);
			}
		})
	})
	return promise
}

// 新建用户
function CreatUser(params, callback){
	var userParams = params || {};
	console.log(userParams);
	var userName   = userParams.name;
	var userMobile = userParams.phone;
	var userPassword = comFunc.md5String(userParams.password);
	// var userHead = userParams.headimg ;
	var timestamp  = Math.round(new Date() / 1000);
	if(!userName || !userMobile || !userPassword )
	{
		if(!userName){  return callback(ErrorCode.noUsername,null)}
		if(!userPassword){return callback(ErrorCode.noPassword,null)}
		if(!userMobile){  return callback(ErrorCode.noMobile,null)}
	}
	else{
		var sessionToken = timestamp +userMobile+ userName + userPassword;
		    sessionToken = crypto.createHash('md5').update(sessionToken).digest('hex');
			userParams.sessiontoken = sessionToken;
			userParams.name = userName;
			userParams.nickname = userName;
			userParams.password  = userPassword;
			userParams.email = "";
			userParams.phone = userMobile;
			userParams.headurl = "";
			userParams.vipstarttime = Math.round(new Date() / 1000);
			userParams.vipendtime = Math.round(new Date() / 1000)+100000;
			User.create(userParams).then(function(resultData){
				var user = resultData.dataValues;
				var data = {
					code:'1',
					message:'success',
					data : {
						sessiontoken : user.sessiontoken
					}
				}
               			return callback(null,data);
			},function(err){
				var errdata = {
					code:"-1",
					message:"用户名或手机号已存在"
				}
				return callback(errdata,null);
			})    
	}
}

//用户手机号登录
function login(params,callback){
	params = params || {};
	if(!params.phone || !params.password){
		 if(!params.phone) {return  callback(ErrorCode.noMobile,null);}
		 if(!params.password) {return  callback(ErrorCode.noPassword,null);}
	}
	else{
		User.findOne({
			where:{
				phone : params.phone,
				password:comFunc.md5String(params.password)
			},
			attributes: ['id','sessiontoken','name'] 
		}).then(function(result){
			if(result){
				var data = {
					code    : '1',
					message : 'success',
					data : {
						userMessage : result.dataValues 
					}
				}
				return callback(null, data);
			}
			else{
				return callback(ErrorCode.loginFaile,null)
			}
	    }, function(err){
	    	var data  = {
					code   : err.parent.errno,
					message: err
				}
	        return callback(err,null);
		})
	}
}

function delUser(params,callback){
	User.destroy({
		where:{
		  phone:params.phone
		}
	}).then(function(){
		return callback(ErrorCode.true);
	})
}

//修改密码
function changePassWordByVcode(params,callback){
	var data = {
		password:params.newpassword
	}
	User.update(data,{
		where:{
			phone:params.phone
		}
	}).then(function(result){
		if(result[0]==0){
			return callback(ErrorCode.loginFaile)
		}else{
			return callback(ErrorCode.true);
		}
	})
}

//修改密码
function changePassWord(params,callback){
	var data = {
		password:params.newpassword
	}
	User.update(data,{
		where:{
			phone:params.phone,
			password:params.oldpassword
		}
	}).then(function(result){
		if(result[0]==0){
			return callback(ErrorCode.loginFaile)
		}else{
			return callback(ErrorCode.true);
		}
	})
}

//三方登陆
//没有账号则新增账号
function thirdLogin(params,callback){
	params = params || {};
	var openid = params.qqOpenId || params.weiboOpenId ||params.weixinOpenId;
	console.log(params);
	var user_qqauthdata;
	if(params.qqOpenId){
		user_qqauthdata = 'qq_openid';
	}else if(params.weiboOpenId){
		user_qqauthdata = 'weibo_openid';
	}
	else if(params.weixinOpenId){
		user_qqauthdata = 'weixin_openid';
	}
	if(!params.qqOpenId && !params.weiboOpenId &&!params.weixinOpenId){
		return  callback(ErrorCode.noOpenId,null);
	}else if(!params.username || !params.avatar){
		return callback(ErrorCode.noParams);
	}else{
		sequelize.query('SELECT `wrzcnet_users`.`user_id` as user_id,`wrzcnet_users`.`sessiontoken`,`wrzcnet_users`.`headimg` as userHead,`wrzcnet_users`.`nickname` FROM `wrzcnet_users` WHERE `'+user_qqauthdata+'` = $2',
			{bind:[user_qqauthdata, openid] }
		).then(function(result){
			if(result[0].length != 0){
				var resultData = result[0][0];
				var userData = {
					user_id  : resultData.user_id,
					nickname :resultData.nickname,
					headimg :resultData.userHead||"",
					sessiontoken:resultData.sessionToken,
				}
				var data = {
					code    : '1',
					message : 'success',
					data : {
						userMessage: result[0][0] 
					}
				}
				//登陆一次增加用户经验一次
				return callback(null, data);
			}else{
				var timestamp  = Math.round(new Date() / 1000);
				var sessionToken = timestamp + params.username + openid;
		    		sessionToken = crypto.createHash('md5').update(sessionToken).digest('hex');
		    	var data = {
		    		user_name:params.username,
		    		nickname:params.nickname.toString(),
					headimg : params.avatar,
		    		sessiontoken:sessionToken,
		    		reg_time : comFunc.getTimeStamp()
		    	}
				if(params.qqOpenId){
					data.qq_openid = openid;
				}else if(params.weiboOpenId){
					data.weibo_openid = openid;
				}
				else{
					data.weixin_openid = openid;
				}
			    User.create(data).then(function(resultData){
					var user = resultData.dataValues;
					var datas = {
						user_id  : user.user_id,
						nickname :user.nickname,
						userHead :user.headimg||"",
						sessiontoken:user.sessiontoken,
					}
					datas = JSON.stringify(datas);
					//保存用户信息
					var params = {
						key : 'USER'+user.ID,
						text: datas
					}
					
					//待返回信息
					var datass = {
						code:'1',
						message:'success',
						data :{
							userMessage: JSON.parse(datas)  
						}
					}
			                     return callback(null,datass);
				},function(err){
					var datasss  = {
						code   :'4000',
						message: err
					}
					return callback(datasss,null);
				})    
			}
			
	    }, function(err){
	    	var datassss  = {
					code   : err.parent.errno,
					message: err
				}
	        return callback(err,null);
		})
	}	
}

//根据一个参数查询用户是否存在
function checkIfUserExit(params,callback){
	params = params || {};
	if(!params){
		return  callback(ErrorCode.noParams,null);
	}else{
		var key = params.key;
		var text= params.text;
		sequelize.query('SELECT COUNT(*) FROM `wrzcnet_users` WHERE `'+key+'` = $1',
			{bind: [text], type: sequelize.QueryTypes.SELECT }
		).then(function(result){
			var count = result[0]['COUNT(*)'];
			if(count != 0){
				return callback('1');
			}
			else{
				return callback('0');
			}
		},function(err){
			console.log(err);
		})
	}	
}

function utf16toEntities(str) {  
    var patt=/[\ud800-\udbff][\udc00-\udfff]/g; // 检测utf16字符正则  
    str = str.replace(patt, function(char){  
            var H, L, code;  
            if (char.length===2) {  
                H = char.charCodeAt(0); // 取出高位  
                L = char.charCodeAt(1); // 取出低位  
                code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00; // 转换算法  
                return "&#" + code + ";";  
            } else {  
                return char;  
            }  
        });  
    return str;  
}  

function getTimeString() {
    return moment().format('YYYY-MM-DD, HH:mm:ss');
}

module.exports.getUserId = getUserId;
module.exports.checkIfUserExit = checkIfUserExit;
module.exports.createUser = CreatUser;
module.exports.thirdLogin  = thirdLogin;
module.exports.getUserIdPromise = getUserIdPromise;
module.exports.login = login;
module.exports.userMessage=userMessage;
module.exports.editUserMessage=editUserMessage;
module.exports.changePassword  = changePassWord;
module.exports.changePassWordByVcode=changePassWordByVcode;
module.exports.delUser=delUser;